<template>
	<div class="page home">
		<div class="btn">
			<van-button plain hairline type="info" size="large" @click="showPopFn" style="">登录</van-button>
		<!-- 	<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumberFn" :plain="true"
				style="border: 0;margin-top: 10rpx;font-size: 26rpx;color: #fff;">授权登录</button> -->
		</div>
		<img class="bg" src="@/static/image/homeBg.png" alt="" />
	</div>

	<van-dialog closeOnClickOverlay use-slot :show="showPop" @close="showPop = false" submit-button-text="登录"
		@submit="submit" :showConfirmButton="false" :showCancelButton="false" width="80%" zIndex="99">
		<div class="popContent flexCenter">
			<img class="userIcon" src="@/static/image/user-icon2.png" alt="" />
			<div class="inputBox">
				<!-- 	<van-field readonly :value="currentServer.name" label="服务器" placeholder="请选择服务器" clearable
					title-width="100rpx" custom-style="border-radius: 10rpx;margin-bottom: 20rpx;" right-icon="arrow"
					@click-icon="showSelectAccountFn('server')" @click-input="showSelectAccountFn('server')" /> -->
				<van-field readonly :value="currentAction.name" label="账套" placeholder="请选择账套" clearable
					title-width="100rpx" custom-style="border-radius: 10rpx;margin-bottom: 20rpx;" right-icon="arrow"
					@click-icon="showSelectAccountFn('account')" @click-input="showSelectAccountFn('account')" />
				<van-field :value="username" v-model="username" label="用户名" placeholder="请输入用户名" clearable
					title-width="100rpx" custom-style="border-radius: 10rpx;margin-bottom: 20rpx"
					@input="(e) => input(e, 'username')" />
				<van-field :value="password" v-model="password" label="密码" placeholder="请输入密码" clearable type="password"
					title-width="100rpx" custom-style="border-radius: 10rpx" @input="(e) => input(e, 'password')" />
			</div>
			<div style="width: 100%">
				<van-button type="info" size="large" @click="submit()">登录</van-button>
			</div>
		</div>
	</van-dialog>
	<van-action-sheet :show="showActionSheet" :actions="actions" z-index="999" @close="showActionSheet = false"
		@select="selectAccount" />
</template>

<script setup lang="ts">
	import { GetServerCommonConfig, loginERP } from '@/api/user';
	import utils from '@/utils';
	import { Utils } from '@/utils/utils';
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, getCurrentInstance } from 'vue';
	import { useStore } from 'vuex';

	const { commit } = useStore();



	/**
	 * 获取用户手机号
	 */
	const getPhoneNumberFn = async (e : any) => {
		if (e.detail.errMsg != 'getPhoneNumber:ok') return;
		// 储存登录类型
		Utils.setStorage('loginType', '客户')
		// 获取手机号吗
		const say = uniCloud.importObject("getPhoneNumber")
		let res = await say.getPhoneNumber(e.detail.code)
		Utils.setStorage('userPhone', res)
		// console.log(res);
		if (res.data.errcode != 0) {
			uni.showModal({
				content: JSON.stringify(res.data.errmsg)
			})
			return;
		}
		username.value = Utils.userName
		password.value = Utils.passWord
		currentAction.value.Id = Utils.acctId
		loginFn()
	}

	// 弹窗
	const showPop = ref(false);
	const showPopFn = () => {
		showPop.value = true;
	};
	/**
	 * 登录数据
	 */
	const currentAction = ref({} as any); // 帐套
	const username = ref(''); // 用户名
	const password = ref(''); // 密码
	// 输入事件
	const input = (e : any, type : string) => {
		type == 'username'
			? (username.value = e.detail)
			: (password.value = e.detail);
	};

	/**
	 * 获取账套列表
	 */
	const getAccountList = async () => {
		// const say = uniCloud.importObject("k3cloud")
		// let res = await say['GetServerCommonConfig']({url:
		//  "/Kingdee.BOS.ServiceFacade.ServicesStub.Account.AccountService.GetDataCenterList.common.kdsvc"})
		const res : any = await GetServerCommonConfig();
		// console.log(res, 'res-----')
		if (res && res.length > 0) {
			actions.value = res.map((item : any) => {
				return {
					name: item.Name,
					id: item.Id,
					...item,
				};
			});
			// 设置默认账套
			currentAction.value = actions?.value[actions.value.length - 1];
		}
	};
	// 服务器列表
	const serverList = ref([
		{
			name: '183.234.22.244',
			url: 'https://183.234.22.244:8090/',
		},
		// {
		//   name: '47.92.202.204',
		//   url: 'http://47.92.202.204',
		// },
	]);
	// 当前服务器
	const currentServer = ref({} as any); // 当前服务器
	/**
	 * 选择帐套逻辑块
	 */
	const popType = ref(''); // 弹窗类型
	const showActionSheet = ref(false); // 是否显示选择帐套
	// 帐套列表
	const actions = ref([] as any); // 帐套列表
	// 显示选择帐套actionSheet
	const showSelectAccountFn = async (type : string) => {
		showActionSheet.value = true;
		popType.value = type;
		if (type == 'server') {
			actions.value = serverList.value;
		} else {
			await getAccountList();
		}
	};
	// 选择
	const selectAccount = async (e : any) => {
		// console.log(actions);
		// 通过名称去找到对应的对象
		const selectedAction = actions.value.find(
			(item : any) => item.name == e.detail.name
		);
		if (popType.value == 'server') {
			currentServer.value = selectedAction;
			utils.setStorage('currentServer', currentServer.value);
			await getAccountList();
		} else {
			currentAction.value = selectedAction;
			utils.setStorage('currentAction', currentAction.value);
		}
	};
	/**
	 * 登录逻辑块
	 */
	const submit = async () => {
		if (!currentAction.value.name) {
			utils.showErr('请选择账套');
			return;
		}
		if (!currentAction.value.Id) {
			utils.showErr('账套信息有误，请重新选择');
			return;
		}
		if (!username.value) {
			utils.showErr('请输入用户名');
			return;
		}
		if (!password.value) {
			utils.showErr('请输入密码');
			return;
		}
		Utils.setStorage('loginType', '内部人员')
		loginFn()

	};

	const loginFn = async () => {
		// const say = uniCloud.importObject("k3cloud")
		// say.login()
		// return;
		const res : any = await loginERP({
			username: username.value,
			password: password.value,
			acctId: currentAction.value.Id,
			lcid: '2052',
		});
		utils.hideLoading();
		if (!res)
			return utils.showErr('登录失败，请检查填写的数据，或者联系管理员！');
		if (res.LoginResultType != 1)
			return utils.showErr(
				res.Message || '登录失败，请检查填写的数据，或者联系管理员！'
			);
		if (res.LoginResultType == 1) {
			commit('user/updateUserInfo', res.Context);
			utils.setStorage('userInfo', res.Context);
			utils.setStorage('KDSVCSessionId', res.KDSVCSessionId);
			// 获取当前登录组织
			const organization = await Utils.getListByFilterValue(Utils.getFormId('组织机构')!,'FName',res.Context.CurrentOrganizationInfo.Name,'','=')
			console.log(organization,'tOrganization');
			if(organization.length > 0){
				Utils.setStorage('currentOrganization',{
					FName:organization[0][1],
					FNumber:organization[0][0]
				})
			}
			utils.showToast(res.Message || '登录成功');
			// 跳转倒tab页
			uni.switchTab({
				url: '/pages/tabs/workbenches/index',
			});
		}
	}
	onLoad(() => {
		// 调用允许发送消息模板
		wx.requestSubscribeMessage({
			tmplIds: ['rAG8ViGLQH99zGxJASwSpTC4zd7OQg0_kk4zNacOUeI'],
		})
		const userPhone = Utils.getStorage('userPhone');
		if (userPhone) {
			username.value = Utils.userName
			password.value = Utils.passWord
			currentAction.value.Id = Utils.acctId
			loginFn()
			return;
		}
		// 设置默认服务器
		currentServer.value = serverList.value[0];
		utils.setStorage('currentServer', currentServer.value);
		getAccountList();

	});
</script>

<style lang="less" scoped>
	.home {
		position: relative;

		.bg {
			width: 100%;
			height: 100%;
		}

		.btn {
			width: 80%;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			bottom: 120rpx;
		}
	}

	.popContent {
		flex-direction: column;
		width: 100%;
		height: 100%;
		padding: 60rpx 30rpx 30rpx;
		background: #f6f6f6;

		.userIcon {
			width: 200rpx;
			height: 200rpx;
			padding: 20rpx 0 0;
		}

		.inputBox {
			width: 100%;
			margin: 20rpx 0 50rpx;
		}
	}
</style>